'use client'

import React, { useState } from 'react'
import { toast } from 'react-hot-toast'
import Button from '@/components/ui/Button'

interface GradeInputProps {
  submissionId: string
  experimentId: string
  currentScore: number | null
  studentName: string
  onScoreUpdated: (newScore: number | null) => void
}

export default function GradeInput({
  submissionId,
  experimentId,
  currentScore,
  studentName,
  onScoreUpdated
}: GradeInputProps) {
  const [score, setScore] = useState<string>(currentScore?.toString() || '')
  const [isUpdating, setIsUpdating] = useState(false)
  const [showInput, setShowInput] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (score === '') {
      toast.error('请输入分数')
      return
    }

    const scoreValue = parseFloat(score)
    if (isNaN(scoreValue) || scoreValue < 0 || scoreValue > 100) {
      toast.error('分数必须在0-100之间')
      return
    }

    setIsUpdating(true)
    toast.loading('正在保存分数...', { id: 'grade-update' })

    try {
      const response = await fetch(`/api/experiments/${experimentId}/submissions/${submissionId}/quick-grade`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ score: scoreValue }),
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(errorData.message || '保存分数失败')
      }

      const data = await response.json()
      onScoreUpdated(scoreValue)
      setShowInput(false)
      toast.success(`已为 ${studentName} 录入分数: ${scoreValue}分`, { id: 'grade-update' })
    } catch (error: any) {
      console.error('保存分数错误:', error)
      toast.error(error.message || '保存分数失败', { id: 'grade-update' })
    } finally {
      setIsUpdating(false)
    }
  }

  const handleCancel = () => {
    setScore(currentScore?.toString() || '')
    setShowInput(false)
  }

  if (!showInput) {
    return (
      <div className="flex items-center space-x-2">
        <span className="text-sm text-gray-600">
          {currentScore !== null ? `${currentScore}分` : '未评分'}
        </span>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowInput(true)}
          className="text-primary-600 hover:text-primary-800"
        >
          {currentScore !== null ? '修改' : '录入'}
        </Button>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="flex items-center space-x-2">
      <input
        type="number"
        value={score}
        onChange={(e) => setScore(e.target.value)}
        placeholder="0-100"
        min="0"
        max="100"
        step="0.1"
        className="w-20 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
        disabled={isUpdating}
        autoFocus
      />
      <Button
        type="submit"
        variant="primary"
        size="sm"
        disabled={isUpdating}
      >
        保存
      </Button>
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={handleCancel}
        disabled={isUpdating}
      >
        取消
      </Button>
    </form>
  )
} 